import axios from 'axios'
import type { AxiosInstance, AxiosRequestConfig } from 'axios'
import { ElMessage } from 'element-plus'
import pinia from '@/stores'
import { useUserStore } from '@/stores/user'

// 获取运行时配置的API地址
const getApiBaseUrl = () => {
  // 开发环境使用环境变量
  if (import.meta.env.DEV && import.meta.env.VITE_API_BASE_URL) {
    return import.meta.env.VITE_API_BASE_URL;
  }
  // 生产环境使用运行时配置
  const mythConfig = (window as any).MYTH_ACADEMY_CONFIG;
  if (mythConfig?.API_BASE_URL) {
    return mythConfig.API_BASE_URL;
  }
  // 默认使用/api路径
  return '/';
};

const service: AxiosInstance = axios.create({
  // 动态获取API地址，支持运行时配置
  baseURL: getApiBaseUrl(),
  timeout: 20000
})

service.interceptors.request.use(
  (config) => {
    const userStore = useUserStore(pinia)
    if (userStore.token) {
      config.headers.Authorization = `${userStore.tokenType} ${userStore.token}`
    }
    return config
  },
  (error) => Promise.reject(error)
)

service.interceptors.response.use(
  (response) => {
    const payload = response.data ?? {}
    const code = payload.code
    if (code === undefined || code === 0 || code === 200) {
      // 直接返回API响应数据，不提取.data
      return payload
    }
    const message = payload.message || '请求失败'
    ElMessage.error(message)
    return Promise.reject(new Error(message))
  },
  (error) => {
    const { response } = error
    let message = error.message || '网络异常，请稍后重试'

    if (response) {
      if (response.status === 401) {
        message = '登录状态已失效，请重新登录'
        const userStore = useUserStore(pinia)
        userStore.forceLogout()
        if (window.location.pathname !== '/login') {
          window.location.href = '/login'
        }
      } else {
        message = response.data?.message || `接口请求失败（${response.status}）`
      }
    }

    ElMessage.error(message)
    return Promise.reject(error)
  }
)

// 简化请求方法，直接返回data
const request = {
  get: <T = any>(url: string, config?: AxiosRequestConfig): Promise<T> => 
    service.get(url, config).then(response => response.data),
  post: <T = any>(url: string, data?: any, config?: AxiosRequestConfig): Promise<T> => 
    service.post(url, data, config).then(response => response.data),
  put: <T = any>(url: string, data?: any, config?: AxiosRequestConfig): Promise<T> => 
    service.put(url, data, config).then(response => response.data),
  delete: <T = any>(url: string, config?: AxiosRequestConfig): Promise<T> => 
    service.delete(url, config).then(response => response.data)
}

export default request
